﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace SnmpForm.BusinessWrapper
{
    public class UserException : Exception
    {
        public UserException(string message):base(message)
        {
        }
    }
    public class User
    {
        //使用单件模式
        static User _instance = null;
        public static User Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new User();
                }
                return _instance;
            }
        }
        private User()
        {
        }

        public class UserRole
        {
            public static int READ = 0;
            public static int NORMAL = 1;
            public static int SUPER = 2;
        }

        public string Hash(string str)
        {
            //建立SHA1对象
            SHA1 sha = new SHA1CryptoServiceProvider();

            //将mystr转换成byte[]
            ASCIIEncoding enc = new ASCIIEncoding();
            byte[] dataToHash = enc.GetBytes(str);

            //Hash运算
            byte[] dataHashed = sha.ComputeHash(dataToHash);

            //将运算结果转换成string
            string hash = BitConverter.ToString(dataHashed).Replace("-", "");

            return hash;
        }

        private DbWrapper.DbDataTypes.User m_userInfo = null;
        public bool Login(string username, string password)
        {
            bool bSuccess = false;
            password = Hash(password);
            if (password != null)
            {
                m_userInfo =
                    DbWrapper.SQLDataOperate.Instance.CheckLogin(username, password);
                if (m_userInfo != null)
                {
                    bSuccess = true;
                }
                else
                {
                    bSuccess = false;
                }
            }
            else
            {
                bSuccess = false;
            }
            return bSuccess;
        }

        //菜单权限
        public bool Permision(object target)
        {
            return Types.Privilege.CheckPermision(target, m_userInfo.roletype);
        }

        public DbWrapper.DbDataTypes.User GetCurrentUserInfo()
        {
            return m_userInfo;
        }

        public void Log(int level, int logtype, string loginfo)
        {
            DbWrapper.SQLDataOperate.Instance.WriteMessage(level, 
                logtype, 
                loginfo, 
                m_userInfo.id);
        }

        /// <summary>
        /// 系统日志查询函数
        /// </summary>
        /// <param name="username">待查询的用户</param>
        /// <param name="level">待查询的级别</param>
        /// <param name="lgtype">待查询的类型</param>
        /// <param name="timeStart">待查询的开始时间</param>
        /// <param name="timeEnd">待查询结束时间</param>
        /// <returns>日志链表</returns>
        public List<DbWrapper.DbDataTypes.LogInfo> SelectLog(
            string username, 
            int level, 
            int lgtype, 
            DateTime timeStart, 
            DateTime timeEnd)
        {
            return DbWrapper.SQLDataOperate.Instance.SelectLog(
                m_userInfo.id,
                username, 
                level, 
                lgtype, 
                timeStart.ToString("yyyy-MM-dd HH:mm:ss"), 
                timeEnd.ToString("yyyy-MM-dd HH:mm:ss"));
        }

        public List<Types.GroupInfo> GetGroup(){
            List<Types.GroupInfo> listGroupInfo = null;
            List<string> listRooms = DbWrapper.SQLDataOperate.Instance.GetFloorIds(m_userInfo.id);
            if (listRooms != null)
            {
                listGroupInfo = new List<Types.GroupInfo>();
                for (int nIndex = 0; nIndex < listRooms.Count; nIndex++)
                {
                    Types.GroupInfo group = new Types.GroupInfo(nIndex, listRooms[nIndex]);
                    listGroupInfo.Add(group);
                }
            }
            return listGroupInfo;
        }

        public List<Ap> GetApList(string strGroup)
        {
            List<Ap> listAp =
                new List<Ap>();
            List<DbWrapper.DbDataTypes.Ap> list = 
                DbWrapper.SQLDataOperate.Instance.GetApList(m_userInfo.id, strGroup);
            if (list != null)
            {
                for (int nIndex = 0; nIndex < list.Count; nIndex++)
                {
                    DbWrapper.DbDataTypes.Ap apinfo = list[nIndex];
                    //解密托管密码
                    DecryptApInfo(apinfo);
                    Ap ap = new Ap(list[nIndex]);
                    listAp.Add(ap);
                }
            }
            return listAp;
        }

        private bool DecryptApInfo(DbWrapper.DbDataTypes.Ap apinfo)
        {
            //解密托管密码
            if (apinfo.snmp_password!=null && apinfo.snmp_password.Length > 0)
            {
                try
                {
                    string plain = AES.AESDecrypt(apinfo.snmp_password);
                    if (plain != null)
                    {
                        apinfo.snmp_password = plain;
                    }
                    else
                    {

                        throw new UserException("解密托管密码出错");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message.ToString());
                    throw new UserException("解密托管密码出错");
                }
            }
            return true;
        }

        public Ap GetAp(int nApId)
        {
            Ap ap = null;
            DbWrapper.DbDataTypes.Ap apinfo = 
                DbWrapper.SQLDataOperate.Instance.GetAp(m_userInfo.id, nApId);
            if (apinfo!=null)
            {
                DecryptApInfo(apinfo);
                ap = new Ap(apinfo);
            }
            return ap;
        }

        public Ap GetAp(string strApFreatureCode)
        {
            Ap ap = null;
            DbWrapper.DbDataTypes.Ap apinfo =
                DbWrapper.SQLDataOperate.Instance.GetAp(m_userInfo.id, strApFreatureCode);
            if (apinfo != null)
            {
                DecryptApInfo(apinfo);
                ap = new Ap(apinfo);
            }
            return ap;
        }

        public bool CreateAp(DbWrapper.DbDataTypes.Ap apinfo)
        {
            //加密托管密码
            if (apinfo.snmp_password!=null)
            {
                if (apinfo.snmp_password.Length > 0)
                {
                    try
                    {
                        string cipher = AES.AESEncrypt(apinfo.snmp_password);
                        if (cipher != null)
                        {
                            apinfo.snmp_password = cipher;
                        }
                        else
                        {
                            throw new UserException("加密托管密码出错");
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message.ToString());
                        throw new UserException("加密托管密码出错");
                    }
                }
            }
            return DbWrapper.SQLDataOperate.Instance.AddAP(m_userInfo.id, apinfo);
        }

        public bool ModifyAp(DbWrapper.DbDataTypes.Ap apinfo)
        {
            DbWrapper.DbDataTypes.Ap info = apinfo.Clone();
            try
            {
                string cipher = AES.AESEncrypt(info.snmp_password);
                if (cipher != null)
                {
                    info.snmp_password = cipher;
                }
                else
                {
                    throw new UserException("加密托管密码出错");
                }
            }
            catch
            {
                throw new UserException("加密托管密码出错");
            }
            return DbWrapper.SQLDataOperate.Instance.ModifyAP(m_userInfo.id, info);
        }
        public bool DelAp(BusinessWrapper.Ap ap)
        {
            return DbWrapper.SQLDataOperate.Instance.DeleteAp(m_userInfo.id, ap.GetInfo().id);
        }
        public bool DelAp(List<int> listAP)
        {
            return DbWrapper.SQLDataOperate.Instance.DeleteAp(m_userInfo.id, listAP);
        }
        public bool ModifyWirelessInfo(BusinessWrapper.Ap ap)
        {
            return DbWrapper.SQLDataOperate.Instance.SetWirelessInfo(m_userInfo.id, 
                ap.GetApWireless());
        }

        public bool ModifyWirelessSecurity(BusinessWrapper.Ap ap)
        {
            return DbWrapper.SQLDataOperate.Instance.SetWirelessSecurity(m_userInfo.id, 
                ap.GetWirelessSecurity());
        }

        public int ApListTemplate(string filepath)
        {
       //     DbWrapper.ExcleDataOperate.Instance.APListTemplateExport();
            return DbWrapper.ExcellibraryHelper.Instance.TemplateExport();
        }
        public bool ApListLoad(ref int nSuccess,ref int nFailure)
        {
        //    return DbWrapper.ExcleDataOperate.Instance.APListImport();
            return DbWrapper.ExcellibraryHelper.Instance.APListImport(ref nSuccess,ref nFailure);
        }

        public int ApListExport(string floorid ,string filepath = "")
        {
        //    return DbWrapper.ExcleDataOperate.Instance.APListExport(m_userInfo.id, floorid);
            return DbWrapper.ExcellibraryHelper.Instance.APListExport(m_userInfo.id, floorid);
        }
        public int ApListExport(List<int> listAp)
        {
            return DbWrapper.ExcellibraryHelper.Instance.APListExport(m_userInfo.id, listAp);
        }

        public List<DbWrapper.DbDataTypes.User> GetUserList()
        {
            return DbWrapper.SQLDataOperate.Instance.GetUserList(m_userInfo.id);
        }

        public DbWrapper.DbDataTypes.User GetUser(int userid)
        {
            return DbWrapper.SQLDataOperate.Instance.GetUser(m_userInfo.id, userid); 
        }

        public bool CreateUser(DbWrapper.DbDataTypes.User user){
            user.password = Hash(user.password);
            return DbWrapper.SQLDataOperate.Instance.CreateUser(m_userInfo.id, user);
        }

        public bool ModifyUser(DbWrapper.DbDataTypes.User user)
        {
            return DbWrapper.SQLDataOperate.Instance.ModifyUser(m_userInfo.id, user);
        }

        public bool DelUser(DbWrapper.DbDataTypes.User user)
        {

            return DbWrapper.SQLDataOperate.Instance.DeleteUser(m_userInfo.id, user.id);
        }

        public List<DbWrapper.DbDataTypes.SearchTarget> GetSearchTargetList()
        {
            return DbWrapper.SQLDataOperate.Instance.GetSearchTarget(m_userInfo.id);;
        }
        public bool AddSearchTarget(DbWrapper.DbDataTypes.SearchTarget target)
        {
            return DbWrapper.SQLDataOperate.Instance.AddSearchTarget(m_userInfo.id, target);
        }
        public bool DelSearchTarget(DbWrapper.DbDataTypes.SearchTarget target)
        {
            return DbWrapper.SQLDataOperate.Instance.DelSearchTarget(m_userInfo.id, target.id);
        }

        public List<DbWrapper.DbDataTypes.SearchTarget> GetApIpPoolSearchTargetList()
        {
            return DbWrapper.SQLDataOperate.Instance.GetApIpPoolSearchTarget(m_userInfo.id); ;
        }
        public bool AddApIpPoolSearchTarget(DbWrapper.DbDataTypes.SearchTarget target)
        {
            return DbWrapper.SQLDataOperate.Instance.AddApIpPoolSearchTarget(m_userInfo.id, target);
        }
        public bool DelApIpPoolSearchTarget(DbWrapper.DbDataTypes.SearchTarget target)
        {
            return DbWrapper.SQLDataOperate.Instance.DelApIpPoolSearchTarget(m_userInfo.id, target.id);
        }

        public bool ModifyDhcpConfig(BusinessWrapper.Ap ap)
        {
            return DbWrapper.SQLDataOperate.Instance.SetDhcp(m_userInfo.id,
                ap.GetDhcpConfig());
        }



        public bool InsertFaultAP(DbWrapper.DbDataTypes.FailureApInfo ap)
        {
            return DbWrapper.SQLDataOperate.Instance.SetFailureAP(m_userInfo.id, ap);
        }

        public Dictionary<int, HashSet<int>> GetFaultApList(string floorid,string strIP,string strMark)
        {
            Dictionary<int, HashSet<int>> mapFaultAp = new Dictionary<int, HashSet<int>>();;
            List<SnmpForm.DbWrapper.DbDataTypes.FailureApInfo> listFailure = 
                DbWrapper.SQLDataOperate.Instance.GetFailureAPList(floorid,strIP,strMark,m_userInfo.id);

            if (listFailure != null)
            {
                HashSet<int> setFault = null;
                bool bExist = false;

                foreach (SnmpForm.DbWrapper.DbDataTypes.FailureApInfo failureAP in listFailure)
                {
                    bExist = mapFaultAp.TryGetValue(failureAP.apid, out setFault);
                    if (!bExist)
                    {
                        setFault = new HashSet<int>();
                        mapFaultAp[failureAP.apid] = setFault;
                    }
                    setFault.Add(failureAP.failureid);
                }
            }

            return mapFaultAp;
        }

        public List<SnmpForm.DbWrapper.DbDataTypes.FailureApInfo> GetApFaultList(int _apid, int _faultType, string _datetime)
        {
            List<SnmpForm.DbWrapper.DbDataTypes.FailureApInfo> listFailure =
                DbWrapper.SQLDataOperate.Instance.GetAPFailureList(_apid,_faultType,_datetime,m_userInfo.id);
            return listFailure;
        }

        public bool ModifyAdvanceTools(BusinessWrapper.Ap ap)
        {
            return DbWrapper.SQLDataOperate.Instance.SetAdvanceTools(m_userInfo.id,
                ap.GetAdvanceTools());
        }
    }
}
